import requests
from datetime import datetime
import json
from os import path

from .message import FETCH_STAFF_WORKTIME_ERROR, FETCH_AREA_INFO_ERROR
from .url_manager import ExistingWorkInfoURL, DeptAreaInfoURL, AreaResourceInfoURL, \
    StartWorkInfoURL, LeaveInfoURL, ShiftInfoURL

to_abs_path = lambda x: path.abspath(path.dirname(__file__)+x)

ExistingWorkInfoFile = to_abs_path("/base_data/ExistingWorkInfo.json")
DeptAreaInfoFile = to_abs_path("/base_data/DeptAreaInfo.json")
AreaResourceInfoFile = to_abs_path("/base_data/AreaResourceInfo.json")
# StartWorkInfoFile = to_abs_path("/base_data/StartWorkInfo.json")
LeaveInfoFile = to_abs_path("/base_data/LeaveInfo.json")
# ShiftInfoFile = to_abs_path("/base_data/ShiftInfo.json")

StartWorkInfoFile = to_abs_path("/base_data/Tmp_StartWorkInfo.json")
ShiftInfoFile = to_abs_path("/base_data/Tmp_ShiftInfo.json")

date_fmt = "%Y-%m-%d"


def get_worktime_by_range(start_date_str, end_date_str, is_data_ol):
    body = {
        "startDate": start_date_str.split(" ")[0],
        "endDate": end_date_str.split(" ")[0]
    }

    data = None
    global ExistingWorkInfoFile

    # 判断是否使用离线数据
    if not is_data_ol:
        with open(ExistingWorkInfoFile, "r") as f:
            data = json.load(f)
    else:
        res = requests.post(url=ExistingWorkInfoURL, json=body)
        if res.status_code == 200:
            data = json.loads(res.content)
        else:
            errMsg = FETCH_STAFF_WORKTIME_ERROR
            errMsg["resultMessage"] += f": {start_date_str}-{end_date_str}"
            return None, errMsg

    # 临时代码，筛选合理数据
    data = [item for item in data 
        if item["startTime"] and item["endTime"]]

    return data, None


def get_area_data(departmentId, Area, is_data_ol):
    dept_area_data, area_resource_data = None, None
    global DeptAreaInfoFile
    global AreaResourceInfoFile

    # 判断是否使用离线数据
    if not is_data_ol:
        # 读取“部门-区域”文件
        with open(DeptAreaInfoFile, "r") as f:
            dept_area_data = json.load(f)
        # 读取“区域-资源”文件
        with open(AreaResourceInfoFile, "r") as f:
            area_resource_data = json.load(f)
    else:
        # 获取“部门-区域“数据
        res = requests.get(url=DeptAreaInfoURL)
        if res.status_code == 200:
            dept_area_data = json.loads(res.content)
        else:
            return None, FETCH_AREA_INFO_ERROR

        # 获取“区域-资源“数据
        res = requests.get(url=AreaResourceInfoURL)
        if res.status_code == 200:
            area_resource_data = json.loads(res.content)
        else:
            return None, FETCH_AREA_INFO_ERROR

    # 开始解析数据
    area_resource_dict = {}
    for item in area_resource_data:
        area_resource_dict[item["id"]] = item

    # 部门与区域资源字典，KEY为区域ID
    dept_data_dict = {
        "craftSeatDtos": {},
        "gateDtos": {},
        "ckicDtos": {},
    } 

    areas = []

    for item in dept_area_data:
        if item["deptId"] == departmentId:
            area = Area(id=item["id"], name=item["name"])
            areas.append(area)
            resource_data = area_resource_dict[item["id"]]

            if resource_data["craftSeatDtos"]:
                for cra in resource_data["craftSeatDtos"]:
                    dept_data_dict["craftSeatDtos"][cra["fullname"]] = area

            if resource_data["gateDtos"]:
                for gat in resource_data["gateDtos"]:
                    dept_data_dict["gateDtos"][gat["fullname"]] = area

            if resource_data["ckicDtos"]:
                for ckic in resource_data["ckicDtos"]:
                    dept_data_dict["ckicDtos"][ckic["fullname"]] = area

    return dept_data_dict, areas


def get_startwork_date(is_data_ol):
    """
    获取员工开始排班日期
    """

    data = None
    global StartWorkInfoFile

    # 判断是否使用离线数据
    if not is_data_ol:
        with open(StartWorkInfoFile, "r") as f:
            data = json.load(f)
    else:
        res = requests.get(StartWorkInfoURL)
        if res.status_code == 200:
            data = res.json()
        else:
            raise Exception("Fail to Fetch Staff WorkTime Info")
       
    return data


def get_staff_leaveinfo(is_data_ol):
    """
    获取员工请休假日期
    """

    data = None
    global LeaveInfoFile

    # 判断是否使用离线数据
    if not is_data_ol:
        with open(LeaveInfoFile, "r") as f:
            data = json.load(f)
    else:
        res = requests.get(LeaveInfoURL)
        if res.status_code == 200:
            data = res.json()
        else:
            raise Exception("Fail to Fetch Staff Leave Info")
       
    return data


def get_shift_info(is_data_ol):
    """
    获取班制信息
    """

    data = None
    global ShiftInfoFile

    # 判断是否使用离线数据
    if not is_data_ol:
        with open(ShiftInfoFile, "r") as f:
            data = json.load(f)
    else:
        res = requests.get(ShiftInfoURL)
        if res.status_code == 200:
            data = res.json()
        else:
            raise Exception("Failed to Fetch Shift Rules")
       
    return data
